package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.entity.AdUser;
import com.heima.model.enums.UserStatusEnum;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import com.heima.model.admin.dtos.LoginResultDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    private static final int EXPIRE_MINUTE = 120;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public LoginResultDTO login(AdUserLoginDto dto) {
        // 根据用户名查用户信息
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, dto.getName());
        AdUser userDB = this.getOne(queryWrapper);
        if(userDB == null){
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        // 密码的匹配
        String passwordDB = userDB.getPassword();
        String passwordInput = dto.getPassword();
        boolean matches = encoder.matches(passwordInput, passwordDB);
        if(!matches){
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 判断用户的状态
        Integer status = userDB.getStatus();
        if(!UserStatusEnum.isValid(status)){
            throw new LeadException(AppHttpCodeEnum.USER_STATUS_ERROR);
        }
        // 生成token，user返回
        LoginResultDTO result = new LoginResultDTO();
        result.setUser(BeanHelper.copyProperties(userDB, AdUserDto.class));
        result.setToken(JwtUtils.generateTokenExpireInMinutes(userDB.getId(), EXPIRE_MINUTE));
        return result;
    }
}
